#include "gstengine.h"
#include "devicefinder.h"

#include <gst/gst.h>
#include <gst/pbutils/pbutils.h>

#include <QtDebug>




GstEngine::GstEngine()
{

}


GstEngine::~GstEngine()
{

}


bool GstEngine::Init()
{
    return true;

}




bool GstEngine::Play(quint64 offset_nanosec)
{
    return true;
}

void GstEngine::Stop()
{

}


GstEngine::PluginDetailsList GstEngine::GetPluginList(
    const QString& classname) const {
  PluginDetailsList ret;

  GstRegistry* registry = gst_registry_get();
  GList* const features =
      gst_registry_get_feature_list(registry, GST_TYPE_ELEMENT_FACTORY);

  GList* p = features;
  while (p) {
    GstElementFactory* factory = GST_ELEMENT_FACTORY(p->data);
    if (QString(gst_element_factory_get_klass(factory)).contains(classname)) {
      PluginDetails details;
      details.name = QString::fromUtf8(gst_plugin_feature_get_name(p->data));
      details.description = QString::fromUtf8(gst_element_factory_get_metadata(
          factory, GST_ELEMENT_METADATA_DESCRIPTION));
      ret << details;
    }
    p = g_list_next(p);
  }

  gst_plugin_feature_list_free(features);
  return ret;
}


/**
* @brief 初始化gststreamer库
* @param
* @return
*/
void GstEngine::InitialiseGstreamer()
{

    qInfo()<<"This called\n";
    gst_init(nullptr, nullptr);
    gst_pb_utils_init();

    QSet<QString> plugin_names;
    for (const PluginDetails& plugin : GetPluginList("Sink/Audio")) {
      plugin_names.insert(plugin.name);
    }


    QList<DeviceFinder*> device_finders;
//    device_finders.append(new DirectSoundDeviceFinder);
    for (DeviceFinder* finder : device_finders) {
      if (!plugin_names.contains(finder->gstreamer_sink())) {
        qInfo() << "Skipping DeviceFinder for" << finder->gstreamer_sink()
                   << "known plugins:" << plugin_names;
        delete finder;
        continue;
      }
      if (!finder->Initialise()) {
        qWarning() << "Failed to initialise DeviceFinder for"
                      << finder->gstreamer_sink();
        delete finder;
        continue;
      }

      device_finders_.append(finder);
    }


}
